package pri.hillchen.springbootstd.sso.config.mybatis;


import org.apache.ibatis.reflection.MetaObject;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by hillchen on 2017/10/20 0020.
 */
public class MetaObjectHandler extends com.baomidou.mybatisplus.mapper.MetaObjectHandler {
    private Map<String,FieldFillHandler> insertNeedFillFields = new HashMap<>();
    {
        insertNeedFillFields.put("id",new IdFieldFillHandler());
        insertNeedFillFields.put("createTime",new DateFieldFillHandler(false));
        insertNeedFillFields.put("updateTime",new DateFieldFillHandler(false));
    }
    private Map<String,FieldFillHandler> updateNeedFillFields = new HashMap<>();
    {
        updateNeedFillFields.put("updateTime",new DateFieldFillHandler(false));
    }
    @Override
    public void insertFill(MetaObject metaObject) {
        fillFieldsByMap(insertNeedFillFields,metaObject);
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        fillFieldsByMap(updateNeedFillFields,metaObject);
    }

    private void fillFieldsByMap(Map<String,FieldFillHandler> fillFields ,MetaObject metaObject){
        for(Map.Entry<String,FieldFillHandler> entry: fillFields.entrySet()){
            FieldFillHandler fieldFillHandler = entry.getValue();
            String fieldName = entry.getKey();
            if(fieldFillHandler.hasField(fieldName,metaObject)){
                Object sourceValue = metaObject.getValue(fieldName);
                if(sourceValue == null){
                    fieldFillHandler.fillField(fieldName,metaObject);
                }
            }
        }
    }
}
